package com.apes.framework.plugin.fsm;

import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.plugin.fsm.snapshot.FsmSnapshotService;
import com.apes.framework.plugin.outbox.annotation.OutBoxExclude;
import com.apes.framework.plugin.soe.metadata.BusinessType;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;
import org.springframework.util.StringUtils;
import org.squirrelframework.foundation.fsm.StateMachineData;

import javax.persistence.*;
import java.io.*;

/**
 * 功能：状态流实例
 *
 * @author xul
 * @create 2020-08-27 11:37
 */
@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = FsmFlowInstance.CONST_TABLE_NAME, indexes = {
        @Index(columnList = "fsm_flow_id, business_key", unique = true)})
public class FsmFlowInstance extends Model {
    public static final String CONST_TABLE_NAME = "fsm_flow_inst";

    @Id
    @Column(name = "id", length = 32)
    @ApesGenerator(code = CONST_TABLE_NAME, name = "状态流实例")
    @Comment("编码")
    private String id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "fsm_flow_id", referencedColumnName = "id", nullable = false)
    @Comment("状态流")
    private FsmFlow fsmFlow;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "business_type", referencedColumnName = "id", nullable = false)
    @Comment("业务单据")
    private BusinessType businessType;

    @Column(name = "business_key", length = 32, nullable = false)
    @Comment("单据编号")
    private String businessKey;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "current_state", referencedColumnName = "id", nullable = false)
    @Comment("当前状态")
    private FsmState currentState;

    @Column(name = "suspend", columnDefinition = "number(1,0) default 0", nullable = false)
    @Comment("是否挂起")
    private boolean suspend = false;

    @Column(name = "finished", columnDefinition = "number(1,0) default 0", nullable = false)
    @Comment("是否结束")
    private boolean finished = false;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "parent", referencedColumnName = "id")
    @Comment("上级节点")
    private FsmStateInstance parent;

    @Lob
    @Basic(fetch = FetchType.LAZY)
    @Column(name = "snapshot", columnDefinition = "CLOB")
    @Comment("状态机快照")
    private String snapshot;

    public StateMachineData.Reader deserialization() {
        String snapshot = SpringManager.getBean(FsmSnapshotService.class).getSnapshot(id);
        if (StringUtils.isEmpty(snapshot)) {
            snapshot = this.snapshot;
        }
        if (StringUtils.isEmpty(snapshot)) return null;
        try (ByteArrayInputStream bis = new ByteArrayInputStream(snapshot.getBytes("ISO-8859-1"));
             ObjectInputStream ois = new ObjectInputStream(bis)) {
            return (StateMachineData.Reader) ois.readObject();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

    public void serialization(StateMachineData.Reader reader) {
        if (reader == null) {
            return;
        }
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
             ObjectOutputStream oos = new ObjectOutputStream(bos)) {
            oos.writeObject(reader);
            String snapshot = new String(bos.toByteArray(), "ISO-8859-1");
            SpringManager.getBean(FsmSnapshotService.class).save(id, snapshot);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
